package cn.simon.free.ratelimiter.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 在普通类中获取注入bean
 *
 * @author simon
 * @date 2020/3/24 17:42
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
@Slf4j
@Order(0)
@Component
public class SpringRateLimitUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringRateLimitUtils.applicationContext == null) {
            SpringRateLimitUtils.applicationContext = applicationContext;
            log.info("======== ApplicationContext配置成功 ========");
        }
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> beanType) {
        return getApplicationContext().getBean(beanType);
    }
}
